package com.sctvcloud.bazhong.ui.utils;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.fragment.BaseGeneraFragment;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.beans.NewsDate;
import com.sctvcloud.bazhong.beans.NewsItem;
import com.sctvcloud.bazhong.beans.Titles;
import com.sctvcloud.bazhong.http.AbsListNetCallback;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.ui.adapter.GreatestAdapter;
import com.sctvcloud.bazhong.ui.util.IListShowData;
import com.sctvcloud.bazhong.utils.ListTypeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liuyu on 2017/8/18.
 */

public class Hour24GetHelper {

    public static final int ERROR_NO_TODAY = 200001;
    public static final int ERROR_NO_YESTERDAY = 200002;
    public static final int ERROR_NO_GETTING = 20001;

    private NewsDate today;
    private NewsDate yesterday;
    private int todayTotal;
    private int yesterDayTotal;
    private int todayPage = -1;
    private int yesterdayPage = -1;
    private boolean shouldSetTitleAfter;
    private boolean hasAddFirtDateTitle;
    private boolean hasAddSecDateTitle;
    private boolean isContinue;
    private boolean isGeting;

    private final String ownerName;

    public Hour24GetHelper(BaseGeneraFragment fragment) {
        ownerName = fragment + "";
    }

    public int get24List(int size, boolean reset, AbsListNetCallback<IListShowData> callback) {
        int re = -1;
        if (isGeting) {
            if (callback != null) {
                callback.onError(null, "this is in gettting", ERROR_NO_GETTING);
                callback.onEnd();
            }
            return re;
        }
        isGeting = true;
        if (reset) {
            reset();
        }
        if (today == null || isTodayGetedAll()) {
            if (isTodayGetedAll()) {
                re = 0;
            } else {
                getYesterday24(size, null, callback);
                re = 2;
            }
        } else {
            re = 1;
            JLog.e("will gettoday");
            getToday24(size, null, callback);
        }
        return re;
    }

    private void getToday24(final int size, final List<IListShowData> lis, AbsListNetCallback<IListShowData> callback) {
        if (today == null) {
            if (callback != null) {
                if (lis != null) {
                    callback.onSuc(lis);
                }
                callback.onError(null, "no today date", ERROR_NO_TODAY);
                callback.onEnd();
                isGeting = false;
            }
            return;
        }
        NetUtils.getNetAdapter().getNewsPage(ownerName, today.getNewsListUrl(), todayPage + 1
                , new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), callback, todayPage + 1) {
                    private ArrayList<IListShowData> list;

                    @Override
                    public void onSuc(List<NewsItem> newsItems) {
                        todayPage = calledIndex;
                        todayTotal = getPageResponse().getData().getPageAll();
                        int to = ListUtils.getTotalSize(lis, list, hasAddFirtDateTitle ? -1 : 0);
                        if (size > 0 && size > to) {
                            isContinue = true;
                            if (isTodayGetedAll()) {
                                if (lis != null) {
                                    lis.addAll(list);
                                    getYesterday24(size, lis, (AbsListNetCallback) obj);
                                } else {
                                    getYesterday24(size, list, (AbsListNetCallback) obj);
                                }
                            } else {
                                if (lis != null) {
                                    lis.addAll(list);
                                    JLog.e("will gettoday " + this);
                                    getToday24(size, lis, (AbsListNetCallback) obj);
                                } else {
                                    JLog.e("will gettoday  " + this);
                                    getToday24(size, list, (AbsListNetCallback) obj);
                                }
                            }
                        } else {
                            if (lis != null) {
                                ((AbsListNetCallback) obj).onSuc(lis.addAll(list));
                            } else {
                                ((AbsListNetCallback) obj).onSuc(list);
                            }
                        }
                    }

                    @Override
                    public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                        list = new ArrayList<>();
                        JLog.e("called index is " + calledIndex + " hase add " + hasAddFirtDateTitle + "   " + this);
                        if (ListUtils.isListValued(newsItems)) {
                            if (calledIndex == 0 || !hasAddFirtDateTitle) {
                                Titles t = new Titles();
                                t.setDateString(DateUtils.formatDate(DateUtils.getDataDate(today), "MM月dd日"));
                                t.setViewType(GreatestAdapter.VIEWTYPE_TITLE_24);
                                hasAddFirtDateTitle = true;
                                list.add(t);
                                if (shouldSetTitleAfter) {
                                    newsItems.get(0).setAfterTitleMode(1);
                                }
                            }
                            list.addAll(newsItems);
                        }
                        return super.doInBackground(newsItems);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        if (lis != null) {
                            ((AbsListNetCallback) obj).onSuc(lis);
                        }
                        ((AbsListNetCallback) obj).onError(ex, errorMsg, netCode);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        JLog.e("in today end is continue=" + isContinue);
                        if (isContinue) {
                            isContinue = false;
                        } else {
                            isGeting = false;
                            ((AbsListNetCallback) obj).onEnd();
                        }
                    }
                });
    }

    private void getYesterday24(final int size, final List<IListShowData> list, AbsListNetCallback<IListShowData> callback) {
        if (yesterday == null) {
            if (callback != null) {
                if (list != null) {
                    callback.onSuc(list);
                }
                callback.onError(null, "no today date", ERROR_NO_YESTERDAY);
                callback.onEnd();
                isGeting = false;
            }
            return;
        }
        NetUtils.getNetAdapter().getNewsPage(ownerName, yesterday.getNewsListUrl(), yesterdayPage + 1
                , new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), callback, yesterdayPage + 1) {
                    private ArrayList<IListShowData> lis;

                    @Override
                    public void onSuc(List<NewsItem> newsItems) {
                        yesterdayPage = calledIndex;
                        yesterDayTotal = getPageResponse().getData().getPageAll();
                        int to = ListUtils.getTotalSize(lis, list, calledIndex == 0 ? -2 : -1);
                        if (size > 0 && size > to) {
                            isContinue = true;
                            if (list != null) {
                                list.addAll(lis);
                                getYesterday24(size, list, (AbsListNetCallback) obj);
                            } else {
                                getYesterday24(size, lis, (AbsListNetCallback) obj);
                            }
                        } else {
                            if (lis != null) {
                                ((AbsListNetCallback) obj).onSuc(list.addAll(lis));
                            } else {
                                ((AbsListNetCallback) obj).onSuc(lis);
                            }
                        }
                    }

                    @Override
                    public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                        lis = new ArrayList<>();
                        if (ListUtils.isListValued(newsItems)) {
                            if (calledIndex == 0) {
                                JLog.e("will add title in yester get has add first " + hasAddFirtDateTitle + "\n " + Hour24GetHelper.this);
                                Titles t = new Titles();
                                t.setDateString(DateUtils.formatDate(DateUtils.getDataDate(yesterday), "MM月dd日"));
                                t.setViewType(hasAddFirtDateTitle ? GreatestAdapter.VIEWTYPE_TITLE_24_CONTINUE : GreatestAdapter.VIEWTYPE_TITLE_24);
                                if (shouldSetTitleAfter) {
                                    newsItems.get(0).setAfterTitleMode(hasAddFirtDateTitle ? 2 : 1);
                                }
                                hasAddFirtDateTitle = true;
                                lis.add(t);
                            }
                            lis.addAll(newsItems);
                        }
                        return super.doInBackground(newsItems);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        if (list != null) {
                            ((AbsListNetCallback) obj).onSuc(list);
                        }
                        ((AbsListNetCallback) obj).onError(ex, errorMsg, netCode);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        JLog.e("in yesterday end is continue=" + isContinue);
                        if (isContinue) {
                            isContinue = false;
                        } else {
                            isGeting = false;
                            ((AbsListNetCallback) obj).onEnd();
                        }
                    }
                });
    }

    private boolean isTodayGetedAll() {
        return todayPage >= 0 && todayTotal <= todayPage + 1;
    }

    private boolean isYesterDayGetedAll() {
        return yesterdayPage >= 0 && yesterDayTotal <= yesterdayPage + 1;
    }

    private void reset() {
        resetToday();
        resetYesterday();
        isContinue = false;
    }

    private void resetToday() {
        JLog.e("resetToday called");
        todayTotal = 0;
        todayPage = -1;
        hasAddFirtDateTitle = false;
    }

    private void resetYesterday() {
        yesterDayTotal = 0;
        yesterdayPage = -1;
    }

    public void setShouldSetTitleAfter(boolean shouldSetTitleAfter) {
        this.shouldSetTitleAfter = shouldSetTitleAfter;
    }

    public void setToday(NewsDate today) {
        if (this.today != today) {
            resetToday();
        }
        this.today = today;
    }

    public void setYesterday(NewsDate yesterday) {
        if (this.yesterday != yesterday) {
            resetYesterday();
        }
        this.yesterday = yesterday;
    }

    public boolean hasGetAll() {
        return (today == null || isTodayGetedAll()) && (yesterday == null || isYesterDayGetedAll());
    }

    public boolean hasValuedDate() {
        return today != null || yesterday != null;
    }


    public static String getDateToString(String milSecond, String pattern) {
        Date date = new Date(Long.valueOf(milSecond));
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }
}
